<script setup>
import { ref, computed, onMounted } from "vue";
import { getWords, updateWordsApi, getNumApi } from "@/api/words";
import { useRouter } from "vue-router";

// 添加组件名称
defineOptions({
  name: "List",
});

const checked = ref("1");
const active = ref(0);
const numArray = ref([]);
const currentWordsLevel0 = ref([]);
const currentWordsLevel1 = ref([]);
const currentWordsLevel2 = ref([]);
const currentWordsLevel3 = ref([]);

const deleteWord = () => {
  showNotify({ type: "success", message: "删除成功", duration: 800 });
};
const num = ref({});
const getList = async () => {
  showLoadingToast({
    message: "加载中...",
    forbidClick: true,
    loadingType: "spinner",
  });
  const { data: data0 } = await getWords(0);
  const { data: data1 } = await getWords(1);
  const { data: data2 } = await getWords(2);
  const { data: data3 } = await getWords(3);
  currentWordsLevel0.value = data0;
  currentWordsLevel1.value = data1;
  currentWordsLevel2.value = data2;
  currentWordsLevel3.value = data3;
  closeToast();
};
const total = computed(() => {
  let total = ref(0);
  numArray.value.forEach((item) => {
    total.value += item.num;
  });
  return total.value;
});
const getNum = async () => {
  const { data } = await getNumApi();
  data.forEach((item) => {
    num.value[item.status] = item.num;
  });
};

onMounted(() => {
  console.log("onMounted");
  getList();
  getNum();
  // getNum();
});
const getRandomElements = (arr, num) => {
  const length = arr.length;
  if (num >= length) return [...arr]; // 若num≥长度，直接返回原数组副本（仅需复制一次）
  if (num <= 0) return [];

  const result = [];
  const selected = new Set(); // 使用Set记录已选索引，保证O(1)查询效率

  while (result.length < num) {
    const randomIndex = Math.floor(Math.random() * length); // 生成随机索引
    if (!selected.has(randomIndex)) {
      // 确保索引未被选中过
      result.push(arr[randomIndex]); // 直接从原数组取值
      selected.add(randomIndex); // 标记索引为已选
    }
  }

  return result;
};

const loading = ref(false);
const onRefresh = () => {
  getList();
  getNum();
  loading.value = false;
  showSuccessToast({
    message: "刷新成功",
    forbidClick: true,
    duration: 300,
  });
};
const selectedChange = async (e, id) => {
  await updateWordsApi(id, e);
  showSuccessToast({
    message: "保存成功",
    forbidClick: true,
    duration: 100,
  });
};

const router = useRouter();

// 跳转到详情页
const goToDetail = (wordId) => {
  console.log(wordId);
  router.push(`/word/${wordId}`);
};
</script>

<template>
  <van-nav-bar :title="'背单词(' + total + ')'" />
  <van-back-top />
  <van-tabs v-model:active="active" sticky="">
    <van-tab :title="'陌生(' + num.status0 + ')'">
      <van-pull-refresh v-model="loading" @refresh="onRefresh">
        <div class="list" v-if="currentWordsLevel0.length > 0">
          <van-swipe-cell
            v-for="(item, index) in currentWordsLevel0"
            :key="index"
          >
            <van-cell :border="false" is-link @click="goToDetail(item.id)">
              <template #title>
                <div class="word">
                  <p>{{ item.word }}</p>
                  <van-radio-group
                    v-model="item.status"
                    direction="horizontal"
                    @change="(e) => selectedChange(e, item.id)"
                    @click.stop
                  >
                    <van-radio :name="0" checked-color="#c8eede"></van-radio>
                    <van-radio :name="1" checked-color="#96f1cb"></van-radio>
                    <van-radio :name="2" checked-color="#54f4b1"></van-radio>
                    <van-radio :name="3" checked-color="#22A6F2"></van-radio>
                  </van-radio-group>
                </div>
              </template>
              <template #label>
                <p class="desc">{{ item.pronunciation }}</p>
                <p class="desc">{{ item.translation }}</p>
              </template>
            </van-cell>
            <template #right>
              <van-button
                square
                type="danger"
                text="删除"
                @click="deleteWord"
              />
            </template>
          </van-swipe-cell>
          <div class="bottom">没有更多了</div>
        </div>
      </van-pull-refresh>
    </van-tab>
    <van-tab :title="'一般(' + num.status1 + ')'">
      <van-pull-refresh v-model="loading" @refresh="onRefresh">
        <div class="list" v-if="currentWordsLevel1.length > 0">
          <van-swipe-cell
            v-for="(item, index) in currentWordsLevel1"
            :key="index"
          >
            <van-cell :border="false" is-link @click="goToDetail(item.id)">
              <template #title>
                <div class="word">
                  <p>{{ item.word }}</p>
                  <van-radio-group
                    v-model="item.status"
                    direction="horizontal"
                    @change="(e) => selectedChange(e, item.id)"
                    @click.stop
                  >
                    <van-radio :name="0" checked-color="#c8eede"></van-radio>
                    <van-radio :name="1" checked-color="#96f1cb"></van-radio>
                    <van-radio :name="2" checked-color="#54f4b1"></van-radio>
                    <van-radio :name="3" checked-color="#22A6F2"></van-radio>
                  </van-radio-group>
                </div>
              </template>
              <template #label>
                <p class="desc">{{ item.pronunciation }}</p>
                <p class="desc">{{ item.translation }}</p>
              </template>
            </van-cell>
            <template #right>
              <van-button
                square
                type="danger"
                text="删除"
                @click="deleteWord"
              />
            </template>
          </van-swipe-cell>
          <div class="bottom">没有更多了</div>
        </div>
      </van-pull-refresh>
    </van-tab>
    <van-tab :title="'不错(' + num.status2 + ')'">
      <van-pull-refresh v-model="loading" @refresh="onRefresh">
        <div class="list" v-if="currentWordsLevel2.length > 0">
          <van-swipe-cell
            v-for="(item, index) in currentWordsLevel2"
            :key="index"
          >
            <van-cell :border="false" is-link @click="goToDetail(item.id)">
              <template #title>
                <div class="word">
                  <p>{{ item.word }}</p>
                  <van-radio-group
                    v-model="item.status"
                    direction="horizontal"
                    @change="(e) => selectedChange(e, item.id)"
                    @click.stop
                  >
                    <van-radio :name="0" checked-color="#c8eede"></van-radio>
                    <van-radio :name="1" checked-color="#96f1cb"></van-radio>
                    <van-radio :name="2" checked-color="#54f4b1"></van-radio>
                    <van-radio :name="3" checked-color="#22A6F2"></van-radio>
                  </van-radio-group>
                </div>
              </template>
              <template #label>
                <p class="desc">{{ item.pronunciation }}</p>
                <p class="desc">{{ item.translation }}</p>
              </template>
            </van-cell>
            <template #right>
              <van-button square type="danger" text="删除" />
            </template>
          </van-swipe-cell>
          <div class="bottom">没有更多了</div>
        </div>
      </van-pull-refresh>
    </van-tab>
    <van-tab :title="'已会(' + num.status3 + ')'">
      <van-pull-refresh v-model="loading" @refresh="onRefresh">
        <div class="list" v-if="currentWordsLevel3.length > 0">
          <van-swipe-cell
            v-for="(item, index) in currentWordsLevel3"
            :key="index"
          >
            <van-cell :border="false" is-link @click="goToDetail(item.id)">
              <template #title>
                <div class="word">
                  <p>{{ item.word }}</p>
                  <van-radio-group
                    v-model="item.status"
                    direction="horizontal"
                    @change="(e) => selectedChange(e, item.id)"
                    @click.stop
                  >
                    <van-radio :name="0" checked-color="#c8eede"></van-radio>
                    <van-radio :name="1" checked-color="#96f1cb"></van-radio>
                    <van-radio :name="2" checked-color="#54f4b1"></van-radio>
                    <van-radio :name="3" checked-color="#22A6F2"></van-radio>
                  </van-radio-group>
                </div>
              </template>
              <template #label>
                <p class="desc">{{ item.pronunciation }}</p>
                <p class="desc">{{ item.translation }}</p>
              </template>
            </van-cell>
            <template #right>
              <van-button square type="danger" text="删除" />
            </template>
          </van-swipe-cell>
          <div class="bottom">没有更多了</div>
        </div>
      </van-pull-refresh>
    </van-tab>
  </van-tabs>
</template>

<style scoped lang="scss">
.list {
  // height: 100vh;
  padding-bottom: 50px;
  .bottom {
    line-height: 50px;
    text-align: center;
    color: rgb(139, 138, 138);
  }
  .van-cell {
    border: 1px solid rgb(239, 238, 238);
    .word {
      display: flex;
      justify-content: space-between;
      p {
        font-size: 18px;
        font-weight: 700;
      }
    }
    .desc {
      color: rgb(88, 87, 87);
    }
  }
  :deep(button) {
    height: 100%;
  }
}
</style>
